package com.midea.listnode;

/**
 * @description：
 * @author: wangwl23
 * @create: 2020-09-21 11:39
 */
public class Leetcode25 {
    public static void main(String[] args) {
        Integer[] a={1,2,3,4,5,7,8,9,10};
        SingleLinkedList<Integer> list = new SingleLinkedList<Integer>(a);
        //reverseKGroup(list,2);
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k <= 1){
            return head;
        }
        ListNode guard = new ListNode(0);
        guard.next = head;
        ListNode previous = guard;
        int count = 1;
        while(head != null){
            if(count == k){
                ListNode tmp = previous.next;
                head =  reverse(previous,head.next);
                previous = tmp;
                if(head == null ){
                    break;
                }
                count = 1;
                continue;
            }
            count ++;
            head = head.next;
        }
        return guard.next;
    }
    private ListNode reverse(ListNode previous, ListNode next){
        ListNode next1 = null;
        ListNode previous1 = next;
        ListNode head = previous.next;
        while(head != next){
            next1 = head.next;
            head.next = previous1;
            previous1 = head;
            head = next1;
        }
        previous.next = previous1;
        return next;
    }
}
